# -*- coding: utf-8 -*-
import logging
import datetime
import hashlib
import uuid
from odoo import api, fields, models
# 生成随机字符串
import random
import string
_logger = logging.getLogger(__name__)


class ApiUsers(models.Model):
    _name = "api.users"
    _description = "接口访问用户"

    def _compute_get_name(self):
        for obj in self:
            obj.name = obj.username

    name = fields.Char(compute='_compute_get_name',
                                    #search='_search_is_create_user',
                                    string='名称',
                                    store=False)

    username = fields.Char(string="用户名", required=True)
    password = fields.Char(string="密码", required=True)
    salt = fields.Char(string="Salt", required=True)
    token = fields.Char(string="Token")
    # generate_date = fields.Datetime(string="Token生成时间", default=fields.datetime.utcnow())
    generate_date = fields.Datetime(string="Token生成时间", default=fields.Datetime.now())
    expired_time_len = fields.Integer(string="过期时间长度(秒)", required=True, default=1800)
    api_user_route_ids = fields.Many2many('api.routes',
                                   'api_users_routes_rel',
                                   'api_user_id',
                                   'api_route_id',
                                   string='可访问接口')
    is_create = fields.Boolean(string='允许录入', default=False, help='这个字段为true时 才能使用创建接口')
    create_code = fields.Char(string="录入编码", help="没有这个编码的时候,不允许创建", copy=False)

    _sql_constraints = [
        ('create_code', 'unique (create_code)', '录入编码唯一')
    ]

    def random_create_code(self):
        """生成18位随机字符串"""
        for i in self:
            if not i.create_code:
                create_code = ''.join(random.sample(string.ascii_letters + string.digits, 16))
                i.create_code = 'Subei'+create_code
            else:
                pass

    @api.model
    def get_token(self):
        """获取token"""
        self.ensure_one()
        generate_datetime = self.generate_date + datetime.timedelta(hours=8)
        now_datetime = fields.datetime.now() + datetime.timedelta(hours=8)
        expired_time_len = datetime.timedelta(seconds=self.expired_time_len)
        # 01 如果超时失效, 重新生成token并返回
        if generate_datetime + expired_time_len < now_datetime:
            self.generate_token()
            return self.token
        else:
            return self.token

    def generate_token(self):
        ''' 生成Token '''
        self.ensure_one()
        # 01.1 获取新的属性值
        new_generate_datetime = fields.datetime.now()
        new_salt = uuid.uuid1()
        md5string = "{}{}{}".format(
            self.username,
            self.password,
            new_salt,
        )
        new_token = "{}".format(
            hashlib.md5(bytes(md5string.encode("utf-8"))).hexdigest()
        )
        # 01.2 新的属性值入库
        self.write({
            "generate_date": new_generate_datetime,
            "salt": new_salt,
            "token": new_token,
        })

    def button_generate_token(self):
        """生成Token"""
        for obj in self:
            obj.generate_token()


class ApiRoutes(models.Model):
    _name = "api.routes"
    _description = "接口访问路由"
    _order = 'sequence'

    name = fields.Char(string="接口名称", required=True)
    route_url = fields.Char(string="接口路由", required=True)
    description = fields.Text(string='备注')
    sequence = fields.Float(string='顺序号', required=True, default=1, digits=(17, 1))


class ApiRecords(models.Model):
    _name = 'api.records'
    _description = 'Api Records'

    doc_type = fields.Char(string='文档类型')
    api_params = fields.Html(string='Json数据')
    api_user_id = fields.Many2one('api.users', string='接口用户')
    api_route = fields.Char(string='接口路由')
    state = fields.Selection([('fail', '失败'), ('success', '成功')], string='状态')
    result_json = fields.Html(string='返回结果')


class ApiConfigParameter(models.Model):
    _name = 's.api.config_parameter'
    _description = 'Api Config Parameter'

    s_key = fields.Char('Key')
    s_value = fields.Char('Value')

